package mastermind.gui.actions;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import mastermind.gui.LoginFrame;
import mastermind.socket.socketConnect;
import mastermind.socket.protocol;

public class SendLoginAction extends AbstractAction{

	private LoginFrame frame;
	
	public SendLoginAction(LoginFrame frame)
	{
		this.frame = frame;
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		String username = frame.getLogin();
		String password = frame.getPassword();
		
		if(username.equals("") || password.equals(""))
		{
			String msg = "Username or password must not be blank";
			JOptionPane.showConfirmDialog((Component) null, msg, "Error", JOptionPane.DEFAULT_OPTION);
		}
		else
		{
			socketConnect connect = frame.getSocket();
			DataInputStream dio = connect.getInputStream();
			DataOutputStream dos = connect.getOutputStream();
			
			if(connect != null && dio != null && dos != null)
			{
				try 
				{
					dos.writeInt(protocol.ATTEMPT_LOGIN); //attempt to login
				} 
				catch (IOException e) 
				{
					e.printStackTrace();
				}

				int response;
				try 
				{
					while((response = dio.readInt()) != protocol.LOGIN_END)
					{
						if(response == protocol.SEND_LOGIN_INFO)
						{
							dos.writeUTF(username);
							dos.writeUTF(password); //send user name and password
						}
						else if(response == protocol.LOGIN_FAILED)
						{
							String msg = "Username or password incorrect";
							JOptionPane.showConfirmDialog((Component) null, msg, "Error", JOptionPane.DEFAULT_OPTION);
						}
						else if(response == protocol.LOGIN_SUCCESS)
						{
							String msg = "Login Successful";
							JOptionPane.showConfirmDialog((Component) null, msg, "Success", JOptionPane.DEFAULT_OPTION);
							frame.setLoginSuccess();
							frame.setUserName(username);
						}
					}
					frame.dispose();
				}
				catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
		}
	}

}
